// ==UserScript==
// @name HTML5tube Buttons
// @match *://www.youtube.com/*
// @author xiaody <xiaody09@163.com>
// @contributor Anoniamto <youtubedownloader@anoniamto.com>
// @date 2012-04
// ==/UserScript==

(function(){
'use strict';
function $(q, p){
	if(arguments.length === 1)
		return document.getElementById(q);
	if(typeof p === "string")
		return p.match(q);
}
HTMLElement.prototype.attr = function(a, b){if(arguments.length===1)return this.getAttribute(a)||'';this.setAttribute(a,b);return this;}
HTMLElement.prototype.append = function(chi){this.appendChild(chi);return this;}

var d = document, lan = d.body.classList[1] || d.documentElement.lang || 'en',
	flag = $("watch-actions") ? 2 : 0,
	k = '', u = '', href = '', r = [], _;
const kTitle = d.title.replace(/"/g, '\'').replace(/!*\?+!*/g, '').replace(/[\\\/:\*<>\|#\.]/g, ''),
	L1 = $('zh',lan) ? ['下载','下载此视频'] : ['Download','Download this video'],
	L2 = $('zh',lan) ? ['循环', '循环播放'] : ['Loop', 'Loop this video'],
	sAnchorAttrs = ' class="yt-uix-button-menu-item" download="' + kTitle + '" ';
const codeTable = {
	'18' : '360p (MP4) ',
	'22' : '720p (MP4) ',
	'34' : '360p (FLV) ',
	'35' : '480p (FLV) ',
	'37' : '1080p(MP4) ',
	'43' : '360p (WebM)',
	'45' : '720p (WebM)'
};

if(flag === 2 && !$("watch-download")) {
	// Generate download-menu's innerHTML(${ul.innerHTML}).
    for(let s = d.scripts, i = s.length; i--;) {
		if($('url_encoded_fmt_stream_map',s[i].text)) {
			k = s[i].text;
			i = 0;
			break;
		}
	}

    if(k)
		r = unescape(k).replace(/\\u0026/g,'&').split('url=');
	else
		return;

    for(let i = 0; ++i<r.length;) {
		if( $('&itag=', _ = r[i]) && (href = _.split('&quality=')[0]) ) {
			let code = +$(/^\d+/g,_.split('&itag=').pop());
			if(code in codeTable)
				u += '<li><a href="' + href + '"' + sAnchorAttrs + '>' + codeTable[code] + '</a>';
		}
	}
	if(!u)
		return;

	const buttonClass = $("watch-share").className, buttonsParent = $("watch-actions");
	// Insert the download button.
	let downloadButton = d.createElement("button").attr("id", 'watch-download').attr("class", buttonClass).attr("title", L1[1]);
	downloadButton.innerHTML = '<span class=yt-uix-button-content>' + L1[0] + '</span>&nbsp;<img class=yt-uix-button-arrow alt>' +
			'<ul class="hid yt-uix-button-menu">' + u + '</ul>';
	buttonsParent.append(downloadButton).append(document.createTextNode(' '));


	// add a loop button.
	var player = $('video-player');
	if ( !player )
		return;

	var loopButton = d.createElement("button").attr("id", 'watch-loop').attr("class", buttonClass).attr("title", L2[1]);
	loopButton.innerHTML = '<span class=yt-uix-button-content>' + L2[0] + '</span>&nbsp;' +
			'<img class="yt-uix-button-icon-playlist-bar-autoplay" src="//s.ytimg.com/yt/img/pixel-vfl3z5WfW.gif" alt>';
	buttonsParent.append(loopButton).append(document.createTextNode(' '));
	loopButton.addEventListener('click', toggleLoop, true);
}

function toggleLoop(){
	'use strict';
	loopButton.classList.toggle('yt-uix-button-toggled');

	var html5Player = document.getElementsByTagName('video')[0];
	if ( !html5Player )
		return;

	if(loopButton.classList.contains('yt-uix-button-toggled')) {
		html5Player.ended && html5Player.play();
		html5Player.attr('loop', '');
	} else
		html5Player.removeAttribute('loop');
}

})();
